package process_management

import (
	"game-time-management/file_manage"
	"game-time-management/types"
	"log"
	"os/exec"
	"strings"
	"time"

	"golang.org/x/text/encoding/simplifiedchinese"
)

var ()

func killProcessByName(name string) error {
	cmd := exec.Command("taskkill", "/F", "/IM", name)
	return cmd.Run()
}

func Process(status *types.StatusExe) {
	prev := file_manage.Read()
	var prevTime [2]time.Time
	if prev[1] == 0 {
		prevTime = [2]time.Time{time.Unix(prev[0], 0), time.Now()}
	} else {
		prevTime = [2]time.Time{time.Unix(prev[0], 0), time.Unix(prev[1], 0)}
	}
	// 如果记录中有当天的记录则赋值上一次启动和关闭时间
	if prevTime[0].Format("2006-01-02") == time.Now().Format("2006-01-02") {
		types.PrevStarted = prevTime[0]
		types.PrevClosed = prevTime[1]
	}

	for {
		for _, exe := range types.ExeName {
			cmd := exec.Command("tasklist", "/NH", "/FI", "IMAGENAME eq "+exe)
			out, err := cmd.CombinedOutput()
			if err != nil {
				log.Println(err)
			}
			output, err := simplifiedchinese.GB18030.NewDecoder().String(string(out))
			if err != nil {
				log.Println(err)
			}
			isRun := !strings.Contains(output, "没有")
			if !(*status)[exe] && isRun {
				// 程序打开
				(*status)[exe] = true
				// 如果上一次启动为0值，则记录启动时间now
				// 否则上一次启动和本次时间为当前时间减去上次使用
				now := time.Now()
				if types.PrevStarted.IsZero() {
					types.Started = now
				} else {
					types.Started = now.Add(types.PrevStarted.Sub(types.PrevClosed))
				}
				file_manage.Write(types.Started.Unix(), now.Unix())
				go func(exe string) {
					for (*status)[exe] {
						switch time.Now().Weekday() {
						case 6, 0:
							watch(time.Since(types.Started), types.Weekend, exe, status)
						default:
							watch(time.Since(types.Started), types.Weekday, exe, status)
						}
						time.Sleep(time.Second * 10)
					}
				}(exe)
			}
		}
		time.Sleep(time.Second * 20)
	}
}

func watch(times, sub time.Duration, name string, status *types.StatusExe) {
	if times > sub {
		// 关闭程序，修改状态， 写入关闭时间
		(*status)[name] = false
		types.PrevClosed = time.Now()
		file_manage.Write(types.Started.Unix(), time.Now().Unix())
		killProcessByName(name)
		return
	}
}
